package public

import (
	"dc-go/global"
	"dc-go/model"
	"dc-go/utils"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"fmt"
)

type ApiLogin struct{}

func (a *ApiLogin) Login(c *gin.Context) {
	var l model.RequestLogin
	if err := model.RequestShouldBindJSON(c, &l); err != nil {
		return
	}
	if l.CaptchaId == "wxc" || global.Store.Verify(l.CaptchaId, l.Captcha, true) {
		u := &model.SysUser{EmpeeAcct: l.EmpeeAcct, Password: l.Password}
		if user, err := servicePublic.ServiceLogin.Login(u); err != nil {
			global.DcLogger.Error(l.EmpeeAcct+" 登录失败, 用户名或密码错误! ", zap.Any("err", err))
			model.ResponseErrorMessage("用户名或密码错误, "+err.Error(), c)
			if err = servicePublic.ServiceLogin.LogLogin(l.EmpeeAcct, c, "no", "登录失败, 用户名或密码错误! "); err != nil {
				global.DcLogger.Error("登录日志记录错误! ", zap.Any("err", err))
			}
		} else {
			a.createToken(*user, c)
		}
	} else {
		model.ResponseErrorMessage("验证码错误! ", c)
		if err := servicePublic.ServiceLogin.LogLogin(l.EmpeeAcct, c, "no", "验证码错误! "); err != nil {
			global.DcLogger.Error("登录日志记录错误! ", zap.Any("err", err))
		}
	}
}

func (a *ApiLogin) createToken(user model.SysUser, c *gin.Context) {
	ss := utils.CreateToken(user.EmpeeAcct)
	if ss == "" {
		global.DcLogger.Error("Jwt配置错误, 请重新初始化数据库! ")
		model.ResponseErrorMessage("Jwt配置错误, 请重新初始化数据库! ", c)
		return
	}
	if err := servicePublic.ServiceLogin.LogLogin(user.EmpeeAcct, c, "yes", "登录成功! "); err != nil {
		global.DcLogger.Error("登录日志记录错误! ", zap.Any("err", err))
	}
	if err := servicePublic.ServiceLogin.SaveOnline(user.EmpeeAcct, ss); err != nil {
		global.DcLogger.Error("记录在线用户失败! ", zap.Any("err", err))
	}
	model.ResponseSuccessMessageData(model.ResponseLogin{
		StaffName: user.StaffName,
		EmpeeAcct: user.EmpeeAcct,
		StaffId:   user.StaffId,
		Token:     ss,
	}, "登录成功! ", c)
}

func (a *ApiLogin) ChangePasswordByCertiNbrAndMobile(c *gin.Context) {
	var l model.RequestChangePasswordByCertiNbrAndMobile
	if err := model.RequestShouldBindJSON(c, &l); err != nil {
		return
	}
	if l.CaptchaId == "wxc" || global.Store.Verify(l.CaptchaId, l.Captcha, true) {
		u := &model.SysUser{}
		md5Password := utils.EncodeMD5(l.CertiNbr)
		fmt.Println(md5Password)
		global.DcDb.Model(u).Where("empee_acct = ?", l.EmpeeAcct).First(&u)
		fmt.Println(u.CertiNbr)
		fmt.Println(md5Password == u.CertiNbr)
		if u.CertiNbr != md5Password || u.Mobile != l.Mobile {
			model.ResponseErrorMessage("身份证号或手机号错误! ", c)
			return
		}
		if l.NewPassword != l.NewPasswordConfirm {
			model.ResponseErrorMessage("两次输入的密码不一致! ", c)
			return
		}
		err := servicePublic.ServiceLogin.ChangePasswordByCertiNbrAndMobile(u, l.NewPassword)
		if err != nil {
			model.ResponseErrorMessage(err.Error(), c)
			return
		} else {
			model.ResponseSuccessMessageData(model.ResponseChangePasswordByCertiNbrAndMobile{
				EmpeeAcct: l.EmpeeAcct,
			}, "修改密码成功! ", c)
		}
	} else {
		model.ResponseErrorMessage("验证码错误! ", c)
	}
}
